<!-- 文章发布页面 -->
<template>
  <div class="add">
    <van-uploader class="upload" :after-read="afterRead" v-model="fileList" multiple :max-count="1" :before-read="beforeRead"></van-uploader>

    <van-cell-group>
      <van-field label="文章标题" v-model="title" placeholder="请输入文章标题" maxlength="20"></van-field>
      <van-field label="文章简介" v-model="summary" placeholder="请输入文章简介"  maxlength="300"></van-field>
      <van-field label="文章内容" v-model="content" placeholder="请输入文章内容" type="textarea"></van-field>
    </van-cell-group>
    <van-button type="warning" @click="handelAdd" class="add-button">提交</van-button>
  </div>
</template>
<script lang="ts">
    import  { Component, Vue } from 'vue-property-decorator'
    import HeaderMenu from '@/components/NavBar.vue'
    import apis from '@/plugins/xhr.ts'

    @Component({
        name: 'home',
        components: {
            HeaderMenu
        }
    })
    export default class Add extends Vue {
        private fileList: any = [];
        private title: string = '';
        private summary: string = '';
        private content: string = '';
        private img: string = '';


        private async handelAdd() {
            if (this.img === '') {
                this.$toast('请上传图片');
                return;
            }
            if (this.title === '') {
                this.$toast('请输入文章标题');
                return;
            }
            if (this.summary === '') {
                this.$toast('请输入文章简介');
                return;
            }
            if (this.content === '') {
                this.$toast('请输入文章内容');
                return;
            }
            const data = {
                img: this.img,
                title: this.title,
                summary: this.summary,
                content: this.content,
            };
            console.log(data);
            const res: any = await apis.createArticle(data);
            if (res.data.success) {
                this.$toast.success('文章发布成功！');
                this.$router.push({
                    name: 'home'
                })
            } else {
                this.$toast.fail(res.data.message)
            }
        }
        // 上传前校验
        private beforeRead(file: any) {
            console.log(file.type)
            if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
                this.$toast('请上传 jpg/png 格式图片');
                return false;
            }

            return true;
        }
        // 文件上传完毕后会触
        private afterRead(file: any) {
            console.log(file);
            this.img = file.content;

        }

    }
</script>
<style scoped>
  .upload >>> .van-uploader__upload {
    width: 10rem;
    height: 10rem;
  }
  .upload >>> .van-uploader__preview-image {
    width: 10rem;
    height: 10rem;
  }
  .add-button {
    margin-top: 3rem;
    width: 100%;
  }
</style>
